package cn.xeblog.plugin.listener;

import cn.hutool.core.io.IoUtil;
import cn.xeblog.plugin.factory.MainWindowFactory;
import cn.xeblog.plugin.ui.MainWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.wm.*;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.io.InputStream;

/**
 * 项目事件监听器
 *
 * @author anlingyi
 * @date 2021/9/4 10:31 下午
 */
public class ProjectEventListener implements ProjectManagerListener {

    /**
     * 窗口标识
     */
    private static final String WINDOW_ID = "XEChat";

    @Override
    public void projectOpened(@NotNull Project project) {
        // 项目打开后，实例化插件主窗口
        MainWindow.getInstance();
    }

    @Override
    public void projectClosed(@NotNull Project project) {
        // 窗口关闭后，这里的操作是由于窗口是单例的，所以当idea多窗口后只有一个窗口被实例化了，当窗口关闭时，实例也被销毁了，则要重新构造窗口
        // idea关闭指定项目后还剩下的项目窗口
        IdeFrame[] allProjectFrames = WindowManager.getInstance().getAllProjectFrames();
        // 其它项目
        Project otherProject = allProjectFrames[0].getProject();
        if (otherProject != null) {
            // 工具栏窗口管理器
            ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(otherProject);
            toolWindowManager.invokeLater(() -> {
                // 通过id获取工具栏窗口
                ToolWindow toolWindow = toolWindowManager.getToolWindow(WINDOW_ID);
                if (toolWindow != null) {
                    try {
                        // 设置图标
                        Icon icon = toolWindow.getIcon();
                        if (icon == null) {
                            InputStream inputStream = ProjectEventListener.class.getResourceAsStream("/images/logo.png");
                            icon = new ImageIcon(IoUtil.readBytes(inputStream));
                        }
                        // 注册的新工具栏窗口任务
                        RegisterToolWindowTask xeChat = RegisterToolWindowTask.notClosable(WINDOW_ID, icon);
                        // 关闭旧的工具栏窗口
                        toolWindow.remove();
                        toolWindow = toolWindowManager.registerToolWindow(xeChat);
                        new MainWindowFactory().createToolWindowContent(otherProject, toolWindow);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
